<template>
  <div class="content-display" ref="contentDisplay">
    <div v-if="!hasContent" class="center-container">
      <!-- 最上面的图片 -->
      <img src="../assets/photo/login/ico.png" alt="中央图片" class="center-image">

      <!-- 内容框 -->
      <div v-if="!isMobileView" class="content-wrapper">
        <!-- 普通对话 -->
        <div class="center-words">
          <p><strong>普通对话</strong></p>
          <p>普通对话是指用户与助手之间的文本消息对话。</p>
        </div>
        <!-- 代码生成 -->
        <div class="center-words">
          <p><strong>代码生成</strong></p>
          <p>代码生成为特色模块。用户通过输入注释、函数名等内容，获取智能生成的函数级代码建议。</p>
        </div>
        <!-- 代码解释 -->
        <div class="center-words">
          <p><strong>代码解释</strong></p>
          <p>代码解释是指用户通过输入代码片段，获取代码片段的解释信息。</p>
        </div>
        <!-- 代码纠错 -->
        <div class="center-words">
          <p><strong>代码纠错</strong></p>
          <p>代码纠错是指精准定位用户代码错误并帮忙纠正。</p>
        </div>
        <!-- 单元测试 -->
        <div class="center-words">
          <p><strong>单元测试</strong></p>
          <p>单元测试是指选中代码，一键生成测试用例。</p>
        </div>
      </div>
    </div>
    <div v-for="(message, index) in content" :key="index" :class="messageClass(message.role)">
      <div class="message-container">
        <div class="message-avatar" :style="avatarStyle(message.role)">
          <el-avatar slot="reference" v-if="message.role === 'user'" id="userInContent"> {{userName}} </el-avatar>
          <img v-else :src="avatarUrl(message.role)" class="avatar-image">
        </div>
        <div class="message-content" :class="{'code-content': isCodeContent(message.content)}">
          <div class="code-wrapper">
            <div class="button-container">
              <button v-if="isCodeContent(message.content)" @click="copyCode(index)" class="copy-button">复制代码</button>
            </div>
            <div v-html="renderedContent(message.content)" :ref="'codeContent' + index" class="code-block-container"></div>
            <div v-if="message.fileName" class="file-attachment">
              <img src="../assets/photo/contentDisplay/file.png" class="file-icon" alt="文件已上传">
              <div class="file-info">
                <span class="file-name">{{ message.fileName }}</span>
                <span class="file-type">文档</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <img src="../assets/photo/contentDisplay/backbottom.png" alt="返回底部" class="scroll-to-bottom" :class="{'is-phone': isPhone}" v-if="showScrollButton" @click="smoothScrollToBottom">
  </div>
</template>

<script>
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';

export default {
  name: 'ContentDisplay',
  props: ['content', 'userName'],
  data() {
    return {
      showScrollButton: false,  // 是否显示“返回底部”按钮
      autoScroll: true,         // 自动滚动标志
      lastScrollTop: 0,         // 用于检测用户的手动滚动行为
      hasContent: false,        // 判断content是否有内容
      isMobileView: window.innerWidth <= 768,   // 判断是否需要显示文字说明
    };
  },
  watch: {
    content(newContent) {
      this.hasContent = newContent.length > 0;
      this.scrollToBottomIfNeeded();
    }
  },
  created() {
    // 在组件创建时检测是否为手机端
    this.isPhone = /mobile|tablet|ip(hone|od|ad)|android/i.test(navigator.userAgent);
  },
  methods: {
    renderedContent(content) {
      const md = new MarkdownIt({
        highlight: function (str, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return '<pre class="code-block"><code class="hljs ' + lang + '">' +
                     hljs.highlight(str, { language: lang }).value +
                     '</code></pre>';
            } catch (__) {}
          }

          return '<pre class="code-block"><code class="hljs">' + md.utils.escapeHtml(str) + '</code></pre>';
        }
      });
      return md.render(content || '');
    },
    messageClass(role) {
      return role === 'user' ? 'user-message' : 'assistant-message';
    },
    avatarUrl(role) {
      return role === 'user' ? '' : require('../assets/photo/login/ico.png');
    },
    avatarStyle(role) {
      const bgColor = role === 'user' ? '#6B92DA' : '#FFF';
      return {
        backgroundColor: bgColor,
        width: '40px',
        height: '40px',
        borderRadius: '50%',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        color: '#FFF',
        fontSize: '12px',
        fontWeight: 'bold',
        marginRight: role === 'user' ? '10px' : '0',
        marginLeft: role === 'user' ? '0' : '10px'
      };
    },
    isCodeContent(content) {
      return content.includes('```');
    },
    copyCode(index) {
      const codeElement = this.$refs['codeContent' + index][0].querySelector('pre.code-block');
      if (codeElement) {
        const textarea = document.createElement('textarea');
        textarea.value = codeElement.innerText; // 只复制代码块的内容
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');  // 复制到剪贴板
        document.body.removeChild(textarea);  // 删除临时元素
        this.$message.success('代码已复制到剪贴板');
      } else {
        this.$message.warning('无法复制代码');
      }
    },
    handleScroll() {
      const container = this.$refs.contentDisplay;
      const tolerance = 10; // 容差值，避免按钮一闪一闪
      const isAtBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - tolerance;

      // 仅当用户手动滚动时才更新 showScrollButton 的状态
      if (container.scrollTop < this.lastScrollTop && !isAtBottom) {
        this.autoScroll = false; // 用户向上滚动，禁用所有自动滚动
        this.showScrollButton = true; // 显示按钮
      } else if (isAtBottom) {
        this.autoScroll = true; // 用户滚动到底部，重新启用自动滚动
        this.showScrollButton = false; // 隐藏按钮
      }

      this.lastScrollTop = container.scrollTop;
    },

    // 平滑滚动到底部 (点击返回底部按钮触发)
    smoothScrollToBottom() {
      const container = this.$refs.contentDisplay;

      // 立即执行滚动，无论 autoScroll 状态如何
      container.style.scrollBehavior = 'smooth';  // 启用平滑滚动
      container.scrollTop = container.scrollHeight + 100; // 滚动到底部，并增加 100 像素的偏移量
      this.showScrollButton = false; // 隐藏返回底部按钮
    },

    scrollToBottomIfNeeded() {
      setTimeout(() => {
        if (this.autoScroll) { // 检查是否在延迟期间检测到用户向上滚动
          this.smoothScrollToBottom(); // 如果没有检测到用户滚动，执行滚动
        }
      }, 100);
    },

    handleResize() {
      this.isMobileView = window.innerWidth <= 768;
    }
  },
  mounted() {
    const container = this.$refs.contentDisplay;
    container.addEventListener('scroll', this.handleScroll);
    this.hasContent = this.content.length > 0; // 初始化 hasContent
    // 检查是否需要显示“返回底部”按钮
    this.handleScroll();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    const container = this.$refs.contentDisplay;
    container.removeEventListener('scroll', this.handleScroll);
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style>
@import 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css'; /* 引入Highlight.js样式 */

.content-display {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  margin-top: 6vh;
  scroll-behavior: smooth;
}

.message-container {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.message-content {
  padding: 10px;
  border-radius: 10px;
  max-width: 45%; /* 对于普通文本，最大宽度为45% */
  word-break: break-word;
  background-color: #eee;
  text-align: left;
  margin-right: 1vw;
  margin-left: 1vw;
  white-space: pre-wrap; /* 确保换行符和空格正常显示 */
  overflow-x: auto; /* 允许水平滚动 */
  position: relative; /* 使复制按钮绝对定位相对于此容器 */
}

.code-wrapper {
  position: relative;
  padding-top: 30px; /* 给复制按钮预留空间 */
}

.button-container {
  position: absolute;
  top: 0;
  right: 0;
  padding-right: 10px;
}

.code-content {
  white-space: nowrap; /* 禁止代码块内容自动换行 */
  max-width: 100%; /* 代码块内容不限制宽度，允许水平滚动 */
  padding: 10px;
  border-radius: 10px;
  position: relative;
}

.code-block {
  padding: 10px;
  border-radius: 10px;
  position: relative;
  background-color: beige;
  border: 1px solid #ccc;
}

.hljs{
  background-color: beige;
}

.message-avatar {
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-image {
  height: 100%;
  border-radius: 50%;
}

.user-message .message-container {
  flex-direction: row-reverse;
  margin-bottom: 20px;
}

.user-message .message-content {
  background-color: #F4F4F4;
}

.assistant-message .message-content {
  background-color: #F4F4F4;
}

.file-attachment {
  display: flex;
  align-items: center;
  margin-top: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #f9f9f9;
}

.file-icon {
  width: 40px;
  height: 40px;
  margin-right: 10px;
}

.file-info {
  display: flex;
  flex-direction: column;
}

.file-name {
  font-weight: bold;
  margin-bottom: 5px;
}

.file-type {
  color: #888;
}

#userInContent {
  font-weight: 400 !important;
}

.scroll-to-bottom {
  position: fixed;
  left: 50%;   
  transform: translateX(-50%);
  width: 45px;
  height: 45px;
  bottom: 80px;  
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000; 
}

.scroll-to-bottom.is-phone {
  left: 54.5%;
  bottom: 150px;
}

.copy-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 12px;
  opacity: 0.8;
  z-index: 10; /* 确保按钮在代码块上方 */
}

.copy-button:hover {
  background-color: #45a049;
  opacity: 1;
}

.center-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  text-align: center;
}

.center-image {
  width: 150px;
  margin-bottom: 20px;
}

.content-wrapper {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 0px;
  max-width: 80vw;
}

.center-words{
  font-size: 14px;
  min-width: 60px;
  max-width: 150px;
  flex: 1; 
  margin: 5px; 
  padding-inline: 10px; 
  border: 1.5px solid #ccc; 
  border-radius: 8px;
}


@media (max-width: 768px) {
  .content-wrapper {
    flex-direction: column;
    align-items: center;
  }
}
</style>
